<template>
  <el-dialog
    v-model="localVisible"
    :title="title"
    width="600px"
    :before-close="handleClose"
    class="role-dialog"
  >
    <template #header>
      <div class="dialog-header">
        <div class="header-content">
          <el-icon class="header-icon"><UserFilled /></el-icon>
          <div class="header-text">
            <h3 class="header-title">{{ title }}</h3>
            <p class="header-subtitle">{{ title.includes('新增') ? '创建新角色信息' : '修改角色信息' }}</p>
          </div>
        </div>
      </div>
    </template>

    <div class="dialog-body">
      <el-form
        ref="formRef"
        :model="localFormData"
        :rules="rules"
        label-position="top"
        class="role-form"
      >
        <div class="form-section">
          <div class="section-header">
            <el-icon class="section-icon"><User /></el-icon>
            <span class="section-title">基本信息</span>
          </div>
          
          <div class="form-grid">
            <el-form-item label="角色Code" prop="name" class="form-item-enhanced">
              <el-input
                v-model="localFormData.name"
                placeholder="请输入角色Code"
                :prefix-icon="UserFilled"
                clearable
              />
            </el-form-item>
            
           <!--  <el-form-item label="角色编码" prop="code" class="form-item-enhanced">
              <el-input
                v-model="localFormData.code"
                placeholder="请输入角色编码"
                :prefix-icon="Key"
                clearable
              />
            </el-form-item> -->
            
<!--            <el-form-item label="角色类型" prop="type" class="form-item-enhanced">-->
<!--              <el-select v-model="localFormData.type" placeholder="选择角色类型">-->
<!--                <el-option label="系统角色" value="system" />-->
<!--                <el-option label="自定义角色" value="custom" />-->
<!--              </el-select>-->
<!--            </el-form-item>-->

           <!--  <el-form-item label="状态" prop="status" class="form-item-enhanced">
              <div class="status-switch-container">
                <el-switch
                  v-model="statusSwitchValue"
                  size="large"
                  active-text="启用"
                  inactive-text="禁用"
                  active-color="#10b981"
                  inactive-color="#ef4444"
                  @change="handleStatusChange"
                />
              </div>
            </el-form-item> -->
          </div>
          
          <el-form-item label="角色描述" prop="description" class="form-item-enhanced form-single">
            <el-input
              v-model="localFormData.description"
              type="textarea"
              :rows="3"
              placeholder="请输入角色描述（可选）"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </div>


      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" class="cancel-btn">
          <el-icon><Close /></el-icon>
          取消
        </el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading" class="submit-btn">
          <el-icon><Check /></el-icon>
          {{ loading ? '保存中...' : '确定' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import {
  User,
  UserFilled,
  Close,
  Check
} from '@element-plus/icons-vue'

interface Role {
  id?: number
  name: string
  code: string
  type: 'system' | 'custom'
  permissions?: string[]
  status: 'active' | 'inactive'
  description?: string
}

interface Props {
  visible: boolean
  title: string
  formData: Partial<Role>
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'submit', data: Partial<Role>): void
  (e: 'cancel'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const loading = ref(false)

// 本地表单数据
const localFormData = reactive<Partial<Role>>({
  name: '',
  code: '',
  type: 'custom',
  permissions: [],
  status: 'active',
  description: ''
})

// 开关状态计算属性
const statusSwitchValue = computed({
  get: () => localFormData.status === 'active',
  set: (value: boolean) => {
    localFormData.status = value ? 'active' : 'inactive'
  }
})

// 处理状态变化
const handleStatusChange = (value: boolean) => {
  localFormData.status = value ? 'active' : 'inactive'
}

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '角色名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { min: 3, max: 20, message: '角色编码长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '角色编码只能包含大写字母和下划线', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择角色类型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}



// 本地可见性控制
const localVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 监听表单数据变化
watch(() => props.formData, (newData) => {
  if (newData && Object.keys(newData).length > 0) {
    Object.assign(localFormData, {
      name: '',
      code: '',
      type: 'custom',
      permissions: [],
      status: 'active',
      description: '',
      ...newData
    })
  }
}, { immediate: true, deep: true })

// 监听弹窗显示状态
watch(() => props.visible, (visible) => {
  if (!visible) {
    resetForm()
  }
})

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    emit('submit', { ...localFormData })
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

// 关闭弹窗
const handleClose = () => {
  emit('cancel')
  localVisible.value = false
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(localFormData, {
    name: '',
    code: '',
    type: 'custom',
    permissions: [],
    status: 'active',
    description: ''
  })
}
</script>

<style scoped>
/* 弹窗整体样式 */
.role-dialog :deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
  background: #ffffff;
}

.role-dialog :deep(.el-dialog__header) {
  padding: 0;
  margin: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.role-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.role-dialog :deep(.el-dialog__footer) {
  padding: 0;
}

.role-dialog :deep(.el-dialog__headerbtn) {
  top: 20px;
  right: 20px;
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  transition: all 0.3s ease;
}

.role-dialog :deep(.el-dialog__headerbtn:hover) {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.1);
}

.role-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  font-size: 18px;
  font-weight: bold;
}

/* 弹窗头部样式 */
.dialog-header {
  padding: 20px;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  font-size: 32px;
}

.header-text {
  flex: 1;
}

.header-title {
  margin: 0 0 4px 0;
  font-size: 20px;
  font-weight: 600;
}

.header-subtitle {
  margin: 0;
  font-size: 14px;
}

/* 弹窗主体样式 */
.dialog-body {
  background: #f8fafc;
}

.role-form {
  max-width: 100%;
}

/* 表单分组样式 */
.form-section {
  margin-bottom: 28px;
  background: white;
  border-radius: 16px;
  padding: 28px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  border: 1px solid #f1f5f9;
  position: relative;
}

.form-section:last-child {
  margin-bottom: 0;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f1f5f9;
}

.section-icon {
  font-size: 20px;
  color: #667eea;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
}

/* 表单网格布局 */
.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  align-items: start;
}

.form-grid .el-form-item {
  margin-bottom: 0;
}

/* 单列表单项 */
.form-single {
  grid-column: 1 / -1;
}

/* 增强的表单项样式 */
.form-item-enhanced {
  margin-bottom: 24px;
}

.form-item-enhanced :deep(.el-form-item__label) {
  font-weight: 600;
  color: #374151;
  font-size: 14px;
  margin-bottom: 8px;
  line-height: 1.5;
}

.form-item-enhanced :deep(.el-input) {
  height: 44px;
}

.form-item-enhanced :deep(.el-input__wrapper) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
  padding: 0 16px;
  height: 44px;
}

.form-item-enhanced :deep(.el-input__wrapper:hover) {
  border-color: #667eea;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.1);
}

.form-item-enhanced :deep(.el-input__wrapper.is-focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-item-enhanced :deep(.el-select .el-input__wrapper) {
  border-radius: 12px;
}

.form-item-enhanced :deep(.el-select) {
  width: 100%;
}

.form-item-enhanced :deep(.el-input__inner) {
  height: 42px;
  line-height: 42px;
}

.form-item-enhanced :deep(.el-textarea__inner) {
  border-radius: 12px;
  border: 1px solid #e2e8f0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.form-item-enhanced :deep(.el-textarea__inner:hover) {
  border-color: #667eea;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.1);
}

.form-item-enhanced :deep(.el-textarea__inner:focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 状态开关样式 */
.status-switch-container {
  display: flex;
  align-items: center;
}

.status-switch-container :deep(.el-switch) {
  --el-switch-on-color: #10b981;
  --el-switch-off-color: #ef4444;
}

.status-switch-container :deep(.el-switch__label) {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

.status-switch-container :deep(.el-switch__label.is-active) {
  color: #10b981;
}

.status-switch-container :deep(.el-switch__label:not(.is-active)) {
  color: #ef4444;
}



/* 弹窗底部样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  padding: 24px 32px;
  background: #f8fafc;
  border-top: 1px solid #e5e7eb;
}

.cancel-btn {
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 600;
  background: #f1f5f9;
  border: 1px solid #d1d5db;
  color: #6b7280;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  background: #e5e7eb;
  border-color: #9ca3af;
  transform: translateY(-1px);
}

.submit-btn {
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 600;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  transition: all 0.3s ease;
}

.submit-btn:hover {
  background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .role-dialog :deep(.el-dialog) {
    width: 95% !important;
    margin: 5vh auto;
  }

  .dialog-header {
    padding: 20px;
  }

  .header-title {
    font-size: 20px;
  }

  .dialog-body {
    padding: 20px;
  }

  .form-section {
    padding: 20px;
    margin-bottom: 20px;
  }

  .form-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .permission-items {
    grid-template-columns: 1fr;
  }

  .dialog-footer {
    padding: 20px;
    flex-direction: column;
  }

  .cancel-btn,
  .submit-btn {
    width: 100%;
  }
}

@media (max-width: 1024px) {
  .role-dialog :deep(.el-dialog) {
    width: 90% !important;
  }

  .form-grid {
    gap: 20px;
  }

  .permission-items {
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  }
}
</style>
